import "../../lib/jquery.js";
import "../../lib/ramda.js";
import direct2d from "../../lib/direct2d.js";
import utils from "../../lib/utils.js";

const Consts = {
    PC_PAGEWIDTH_RATE: 0.53,
    template: {
        word: $("ux-template#word").html(),
        br: `<div style="height:100%"></div>`,
    },
}

const State = {
    _frame_fns: [],
    _event_quene: [],
}

function frame_join(fn) {
    State._frame_fns.push(fn)
}

function event_push(name, val) {
    State._event_quene.push([name,val])
}

function event_poll(name) {
    const i = R.findIndex((a)=>(a[0] == name), State._event_quene)
    return {
        on(fn){
            if (i >= 0) {
                const val = State._event_quene[i][1]
                const fn_take = ()=>{
                    if (State._event_quene.length > 1) {
                        State._event_quene[i] = State._event_quene.at(-1)
                    }
                    if (State._event_quene.length > 0) {
                        State._event_quene.pop()
                    }
                }
                fn(val, fn_take)
            }
        }
    }
}

function editor(dom) {
    const dom_words = dom.children("#words")

    dom_words.focusin(()=>{
        console.log("dom.focusin")
        event_push("use-ime-in")
    })

    dom_words.on("click", ()=>{
        console.log("dom.click")
        event_push("use-ime-in")
    })

    dom_words.on("mouseenter", ()=>{
        $("#_ime_in").trigger("focus")
        event_push("use-ime-in")
    })

    function on_frame() {
        event_poll("ime-in").on((val, fn_take)=>{
            for (const a of val) {
                dom_words.append(R.replace("{WORD}", a, Consts.template.word))
            }
            fn_take()
        })
        event_poll("ime-key").on((keyname, fn_take)=>{
            if ("Enter" == keyname) {
                dom_words.append(Consts.template.br)
            } else if ("Backspace" == keyname) {
                dom_words.children(".word").last().remove()
            }
            fn_take()
        })
    }

    frame_join(on_frame)
}

function tabmenu(dom, init_id) {
    const tabs = direct2d.Tabs(dom, {
        on_select(me){
            me.class_add("cur")
            direct2d.Item(me.ux_value()).visible(true)
        },
        on_unselect(me){
            me.class_del("cur")
            direct2d.Item(me.ux_value()).visible(false)
        },
        on_mouse_enter(me){
            tabs.select(me)
        },
    }).select_with_val(init_id)
}

function ime_in(dom) {
    let in_composing = false
    function submit(){
        const val = dom.val()
        dom.val("")
        event_push("ime-in", val)
    }
    dom.on("compositionstart", function(){
        in_composing = true
    })
    dom.on("compositionend", function(){
        in_composing = false
        submit()
    })
    dom.on("focusout", function(){
    //    dom.trigger("focus")
    })
    dom.on("input", function(){
        if (! in_composing) {
            submit()
        }
    })
    dom.on("keyup", (data)=>{
        console.log(data.key)
        if (["Enter","Backspace"].indexOf(data.key) >= 0) {
            event_push("ime-key", data.key)
        }
    })
    //dom.trigger("focus")
    frame_join(()=>{
        event_poll("use-ime-in").on((_, fn_take)=>{
            dom.trigger("focus")
            fn_take()
        })
    })
}

function events() {
    $(document.body).on("click", ()=>{
        $(document.body).trigger("focus")
    }).on("mouseenter", ()=>{
        $(document.body).trigger("focus")
    })
}

function init() {
    if ("pc" == direct2d.adaption_mobile_width(Consts.PC_PAGEWIDTH_RATE)) {
    }
    events()
    editor($("#box-edit-area"))
    tabmenu("#tabs", "#box-edit")
    ime_in($("#_ime_in"))
}

function on_frame() {
    R.forEach(R.applyTo(undefined), State._frame_fns)
}

export default {
    init,
    on_frame,
}
